package com.burning.myburning;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.ocm.burnningstar.GlobalApplication;
import com.shape.sdk.Course;
import com.shape.sdk.Fitness;
import com.shape.sdk.FitnessData;
import com.shape.sdk.ShapeCenter;

import java.util.List;

/**
 * Created by ouzhiyin on 24/01/2018.
 */

public class TestShapeInterface {
  Handler handler;
  ShapeCenter shapeCenter;
  Fitness fitness;
  Course course;
  long courseStartTime = 0;
  long courseStopTime = 0;
  int workingCount = 0;
  long currentVideoDuration = 0;
  int currentVideoPlayNum = 0;
  List<Course.VideoUnit> playList = null;

  final static long MINUTES_15 = 15 * 60 * 1000;
  final static long STOP_SHOW_TIME = 15 * 1000;

  public TestShapeInterface() {
    handler = new Handler(Looper.getMainLooper());
  }

  public void startTest() {
    Log.d("shapesdk", "!!!!!!Test Start !!!!!!!");
//    shapeCenter = GlobalApplication.getShapeCenter();
    // 初始化的时候把 init.json 文件放在 /sdcard/shapefitness 下面
    shapeCenter.init(new ShapeCenter.Listener() {

      @Override
      public void onEvent(ShapeCenter.PublicNotifyType type, long doTimestamp) {
        Log.d("shapesdk", "ON EVENT " + type);
        long delay;
        switch (type) {
          case START:
            // TODO 1cm 这个 delay 的时间用作课程一开始的准备时间
            delay = doTimestamp - System.currentTimeMillis();
            if (delay > 0) {
              handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                  if (fitness != null && fitness.getState() == Fitness.State.READY) {
                    start(System.currentTimeMillis());
                  }
                }
              }, delay);
            } else {
              start(System.currentTimeMillis());
            }
            break;
          case STOP:
            stop(System.currentTimeMillis());
            break;
          default:
            // 异常情况 不可能
            throw new RuntimeException();
        }
      }
    });
    // 开始运行状态机
    working();
  }

  private void working() {
    // 5 秒检查一次状态
    if (workingCount % 5 == 0) {
      stateCheck();
    }

    // 2 秒刷新一次数据
    if (workingCount % 2 == 0) {
      refreshData();
    }

    ++workingCount;
    if (workingCount == 10) {
      workingCount = 0;
    }
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        working();
      }
    }, 1000);
  }

  private void stateCheck() {
    if (course == null) {
      // 上节课刚结束或者刚刚开机
      course = shapeCenter.getNextCourse(0);
    }
    if (course == null) {
      Log.d("shapesdk", "no course");
      return;
    }
    if (fitness == null) {
      fitness = shapeCenter.loadCourse(course);
      Log.d("shapesdk", "load course: " + course.getScheduleId());
    }
    if (fitness == null) {
      // 异常情况 不可能
      throw new RuntimeException();
    }

    long currentTime = System.currentTimeMillis();
    switch (fitness.getState()) {
      case INIT:
        // 异常情况 不可能
        throw new RuntimeException();
      case READY:
        // 判断是否该课程已经过了开始时间
        // 在该时间段可以访问链接开始课程
        // http://fit.runninglemon.com/api/v1/coach/test_start?store_id=1
        // 可以通过下面这个链接添加签到的用户, 其中 xxx 是字符串，每个用户需要不同
        // http://fit.runninglemon.com/api/v1/booking/test_bind?device_id=xxxx
        // Warning getStartTime 的单位都是毫秒
        if (currentTime > course.getStartTime() + MINUTES_15) {
          stop(currentTime);
          Log.d("shapesdk", "this course not start and stop it : " + course.getScheduleId());
        }
        break;
      case RUNNING:
        // 判断是否该课程已经结束
        // 在该时间段可以访问链接结束课程
        // http://fit.runninglemon.com/api/v1/coach/test_finish?store_id=1
        if (currentTime > courseStartTime + course.getDuration() * 1000) {
          stop(currentTime);
          Log.d("shapesdk", "this course stop by auto : " + course.getScheduleId());
        }
        break;
      case PAUSE:
        // 异常情况 不可能
        throw new RuntimeException();
      case STOP:
        // 判断结束展示时间是否结束，结束后进度下一节课
        // 在该时间段可以访问链接结束课程
        // http://fit.runninglemon.com/api/v1/coach/test_finish?store_id=1
        if (currentTime > courseStopTime + STOP_SHOW_TIME) {
          finish();
          Log.d("shapesdk", "course finish");
        }
        break;
    }
  }

  private void refreshData() {
    if (course == null || fitness == null) {
      // 没有加载出任何内容，返回
      return;
    }
    switch (fitness.getState()) {
      case INIT:
        // 异常情况 不可能
        throw new RuntimeException();
      case READY:
      case RUNNING: {
        List<FitnessData> showFitnessDatas = fitness.getUsersFitness();
        if (showFitnessDatas == null || showFitnessDatas.size() == 0) {
          Log.d("shapesdk", "no users");
        } else {
          // TODO 1cm 显示这些数据到卡片
          for (FitnessData fitnessData : showFitnessDatas) {
            Log.d("shapesdk", fitness.getState() + " user :" + fitnessData.getUser().getUserId()
                    + " heartRate:" + fitnessData.getHeartRate()
                    + " calories:" + fitnessData.getCalories());
          }
        }
        if (fitness.getState() == Fitness.State.RUNNING) {
          nextLogic(System.currentTimeMillis());
        }
      }
      break;
      case PAUSE:
        // 异常情况 不可能
        throw new RuntimeException();
      case STOP: {
        List<FitnessData> showFitnessDatas = fitness.getResultReport();
        for (FitnessData fitnessData : showFitnessDatas) {
          // Warning getCalories 小卡，换算成显示的卡路里需要除以1000
          Log.d("shapesdk", "STOP user :" + fitnessData.getUser().getUserId()
                  + " heartRate:" + fitnessData.getHeartRate()
                  + " calories:" + fitnessData.getCalories());
        }
      }
      break;
    }
  }

  private void nextLogic(long currentTime) {
    if (course.getType() != 2) {
      return;
    }
    if (currentTime - courseStartTime > currentVideoDuration * 1000
            && currentVideoPlayNum < playList.size()) {
      if (playList.get(currentVideoPlayNum).getGoNext()) {
        fitness.next();
        Log.d("shapesdk", "next!!!!!!");
      }
      currentVideoPlayNum++;
      if (currentVideoPlayNum < playList.size()) {
        // Warning SDK 所有 duration 时间相关的单位都是秒
        currentVideoDuration += playList.get(currentVideoPlayNum).getVideDuration();
      }
    }
  }

  private void start(long currentTime) {
    if (fitness == null || fitness.getState() != Fitness.State.READY) {
      return;
    }
    fitness.start();
    courseStartTime = currentTime;

    // TODO 1cm
    // 播放视频和音频逻辑
    //=================

    // Warning Type 的含义发生了变化
    // 1 操课 只播放音频
    // 2 圈课 播放视频和音频
    // 3 课间操 播放视频和音频 (有可能没有心率用户显示)
    if (course.getType() == 2) { // 圈课（播放视频的课）
      playList = course.getPlayList();
      currentVideoPlayNum = 0;
      // 不可能出现 playlist 为空的情况，在圈课的情况下
      currentVideoDuration = playList.get(0).getVideDuration();
    }
  }

  private void stop(long currentTime) {
    if (fitness == null || fitness.getState() == Fitness.State.STOP) {
      return;
    }
    // Warning 接口发生了变化，原来的 finish 变成了 stop
    fitness.stop();
    courseStopTime = currentTime;
  }

  private void finish() {
    course = null;
    fitness = null;
    courseStartTime = 0;
    courseStopTime = 0;
    currentVideoDuration = 0;
    currentVideoPlayNum = 0;
    playList = null;
  }

}
